package me.yricky.alia.utils.gds

import java.io.InputStream
import java.nio.ByteBuffer

/**
 * @author Yricky
 * @date 2022/1/28
 */
class GDS2Iterator(private val inS: InputStream):Iterator<GDS.Record.Raw> {

    private val recordBuffer : ByteBuffer = ByteBuffer.allocate(0x10000)
    private var nextRecord:GDS.Record.Raw = getRecord()

    private fun getRecord(): GDS.Record.Raw {
        recordBuffer.clear()
        val ba = ByteArray(4)
        if(inS.read(ba) != 4){
            return GDS.Record.Invalid
        }
        recordBuffer.put(ba)
        recordBuffer.rewind()

        val length = recordBuffer.short
        val type = recordBuffer.short

        if(type == 0.toShort() || length == 0.toShort()){
            return GDS.Record.Invalid
        }

        val content = ByteArray(length.toInt()-4)
        inS.read(content)
        return GDS.Record.Raw(length, GDS.recordType(type), content)
    }

    override fun hasNext(): Boolean {
        return nextRecord != GDS.Record.Invalid
    }

    override fun next(): GDS.Record.Raw {
        val ret = nextRecord
        nextRecord = getRecord()
        return ret
    }
}